package com.color.service.impl;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;
import org.springframework.web.context.request.WebRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.color.dao.IOpenNoDao;
import com.color.dao.IServiceNoDao;
import com.color.dao.IUserNoDao;
import com.color.entity.OpenNo;
import com.color.entity.ServiceNo;
import com.color.entity.UserNo;
import com.color.service.IUserNoService;
import com.color.utils.ObjectUtils;

@Service("userNoService")
public class UserNoServiceImpl implements IUserNoService{
	
	@Autowired
	@Qualifier("userNoDao")
	private IUserNoDao userNoDao;
	
	@Autowired
	@Qualifier("openNoDao")
	private IOpenNoDao openNoDao;
	
	@Autowired
	@Qualifier("serviceNoDao")
	private IServiceNoDao serviceNoDao;

	public Map<String,Object> getPageList(ModelMap model,WebRequest request){
		
		String page = request.getParameter("page");
		String rows = request.getParameter("rows");
		String sNo = request.getParameter("sNo");
		
		List<UserNo> list = userNoDao.getPageList(ObjectUtils.stringToInt(page), ObjectUtils.stringToInt(rows),sNo);
		int total = userNoDao.getCountList(sNo);
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("rows", list);
		map.put("total", total);
		return map;
	}
	
	public Map<String,Object> commitData(WebRequest request){
		
		String deleted = request.getParameter("deleted");
		String inserted = request.getParameter("inserted");
		String updated = request.getParameter("updated");
		
		if(deleted != null){
			//把json字符串转换成对象
		    List<UserNo> listDeleted = JSON.parseArray(deleted, UserNo.class);
		    for(UserNo ser : listDeleted){
		    	userNoDao.Delete(ser);
		    }
		}
		if(inserted != null){
		    //把json字符串转换成对象
		    List<UserNo> listInserted = JSON.parseArray(inserted, UserNo.class);
		    for(UserNo ser : listInserted){
		    	userNoDao.Save(ser);
		    }
		}
		if(updated != null){
		    //把json字符串转换成对象
		    List<UserNo> listUpdated = JSON.parseArray(updated, UserNo.class);
		    for(UserNo ser : listUpdated){
		    	userNoDao.Save(ser);
		    }
		}
		
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("iRet", "0");
		map.put("strMsg", "操作成功!");
		return map;
	}
	

	
	/**
	 * 开奖操作
	 */
	public Map<String,Object> oprUserColor(WebRequest request){
		
		Map<String,Object> map = new HashMap<String, Object>();
		
		String sNo = request.getParameter("sNo");
		
		if(sNo != null && !"".equals(sNo)){
			List<UserNo> list = userNoDao.getColorList(sNo);
			
			if(list == null || list.size() == 0){
				map.put("iRet", "-1");
				map.put("strMsg", "没有要兑奖的记录!");
				return map;
			}
			
			OpenNo openNo = openNoDao.getOpenBysNo(sNo);
			if(openNo == null){
				
				//自动开奖
				openNo = getSysOpenNo();
				
				if(openNo == null){
					map.put("iRet", "-1");
					map.put("strMsg", "获取开奖号码失败!");
					return map;
				}
				
				if(!sNo.equals(openNo.getsNo())){
					map.put("iRet", "-1");
					map.put("strMsg", "["+sNo+"]开奖时间未到,请耐心等待!");
					return map;
				}else{
					//添加
					openNoDao.Save(openNo);
				}
				
			}
			
			//兑奖
			int iRet = openColorList(list,openNo);
			
			if(iRet < 0){
				map.put("iRet", "-1");
				map.put("strMsg", "开奖号码有误,请查证!");
				return map;
			}
			
			//更新开奖结果
			userNoDao.Save(list);
			
			map.put("iRet", "0");
			map.put("strMsg", "兑奖成功!");
			
		}else{
			map.put("iRet", "-1");
			map.put("strMsg", "请输入彩票期号!");
		}
		
		return map;
	}
	
   /**
    * 开奖算法	
    * @param list
    * @param openNo
    */
   public int openColorList(List<UserNo> list,OpenNo openNo){
	   
	   int iRet = 0;
	   
	   int index = 0;
	   boolean flag = false;
	   String steText = "";
	   
	   String[] color = new String[6]; 
	   String blue = "";
	   
	   if(openNo.getRedColor1()== null && "".equals(openNo.getRedColor1())){
		  return -1;
	   }else{
		   color[0] = openNo.getRedColor1();
	   }
	   
	   if(openNo.getRedColor2()== null && "".equals(openNo.getRedColor2())){
		  return -1;
	   }else{
		   color[1] = openNo.getRedColor2();
	   }
	   
	   if(openNo.getRedColor3()== null && "".equals(openNo.getRedColor3())){
		  return -1;
	   }else{
		   color[2] = openNo.getRedColor3();
	   }
	   
	   if(openNo.getRedColor4()== null && "".equals(openNo.getRedColor4())){
		  return -1;
	   }else{
		   color[3] = openNo.getRedColor4();
	   }
 
	   if(openNo.getRedColor5()== null && "".equals(openNo.getRedColor5())){
		  return -1;
	   }else{
		   color[4] = openNo.getRedColor5();
	   }
	   
	   if(openNo.getRedColor6()== null && "".equals(openNo.getRedColor6())){
		  return -1;
	   }else{
		   color[5] = openNo.getRedColor6();
	   }
	   
	   if(openNo.getBuleColor1()== null && "".equals(openNo.getBuleColor1())){
		  return -1;
	   }else{
		   blue = openNo.getBuleColor1();
	   }
	   
	   for(UserNo uNo : list){
		   index = 0;
		   flag = false;
		   steText = "中奖号码为: 红球";
		   
		   //对比中奖号码
		   if(checkRed(color,uNo.getRedColor1())){
			   steText += "  <span style='color:red'>"+uNo.getRedColor1()+"</span>";
			   index++;
		   }else{
			   steText += "  "+uNo.getRedColor1();
		   }
		   
		   if(checkRed(color,uNo.getRedColor2())){
			   steText += "  <span style='color:red'>"+uNo.getRedColor2()+"</span>";
			   index++;
		   }else{
			   steText += "  "+uNo.getRedColor2();
		   }
		   
		   if(checkRed(color,uNo.getRedColor3())){
			   steText += "  <span style='color:red'>"+uNo.getRedColor3()+"</span>";
			   index++;
		   }else{
			   steText += "  "+uNo.getRedColor3();
		   }
		   
		   if(checkRed(color,uNo.getRedColor4())){
			   steText += "  <span style='color:red'>"+uNo.getRedColor4()+"</span>";
			   index++;
		   }else{
			   steText += "  "+uNo.getRedColor4();
		   }
		   
		   if(checkRed(color,uNo.getRedColor5())){
			   steText += "  <span style='color:red'>"+uNo.getRedColor5()+"</span>";
			   index++;
		   }else{
			   steText += "  "+uNo.getRedColor5();
		   }
		   
		   if(checkRed(color,uNo.getRedColor6())){
			   steText += "  <span style='color:red'>"+uNo.getRedColor6()+"</span>";
			   index++;
		   }else{
			   steText += "  "+uNo.getRedColor6();
		   }
		   
		   steText += " 蓝球";
		   
		   if(blue.equals(uNo.getBuleColor1())){
			   steText += "  <span style='color:blue'>"+uNo.getBuleColor1()+"</span>";
			   flag = true;
		   }else{
			   steText += "  "+uNo.getBuleColor1();
		   }
		   
		   //获取获奖级别
		   String[] strs = getColorLevel(index,flag);
		   
		   String level = strs[0];
		   String text = strs[1] + steText;
		   
		   uNo.setColorLevel(level);
		   uNo.setColorText(text);
		   
	   }
	   
	   
	   return iRet;
   }
   
   //判断红球是否中奖
   public boolean checkRed(String[] strs,String red){
	   boolean flag = false;
	   for(String str : strs){
		   if(str.equals(red)){
			   flag = true;
			   break;
		   }
		   
	   }
	   
	   return flag;
   }
   
   /**
    * 判断获奖级别
    * @param index
    * @param flag
    * @return
    */
   public String[] getColorLevel(int index,boolean flag){
	   
	   String[] strs = null;
	   String strFlag = "";
	   String strIndex = String.valueOf(index);
	   if(flag){
		   strFlag = "1";
	   }else{
		   strFlag = "0";
	   }
	   
	   strIndex += strFlag;
	   
	   if("61".equals(strIndex)) {
	      strs = new String[]{"1","恭喜中了一等奖"};
	      
	   }else if("60".equals(strIndex)){
		  strs = new String[]{"2","恭喜中了二等奖"};
		  
	   }else if("51".equals(strIndex)){
		  strs = new String[]{"3","恭喜中了三等奖"};
		  
	   }else if("50".equals(strIndex) || "41".equals(strIndex)){
		  strs = new String[]{"4","恭喜中了四等奖"};
		  
	   }else if("40".equals(strIndex) || "31".equals(strIndex)){
		  strs = new String[]{"5","恭喜中了五等奖"};
		  
	   }else if("21".equals(strIndex) || "11".equals(strIndex) || "01".equals(strIndex)){
		  strs = new String[]{"6","恭喜中了六等奖"};
	   }else{
		   strs = new String[]{"0","请再接再厉"};
	   }
	   
	   return strs;
   }
   
   /**
    * 调用系统的开奖结果
    * @return
    */
   public OpenNo getSysOpenNo(){
	   String httpUrl = "http://apis.baidu.com/apistore/lottery/lotteryquery";
		String httpArg = "lotterycode=ssq&recordcnt=1";
		String jsonResult = request(httpUrl, httpArg);
		
		JSONObject obj = JSONObject.parseObject(jsonResult);
		String retMsg = obj.getString("retMsg");
		List<OpenNo> lOpen = new ArrayList<OpenNo>();
		if("success".equals(retMsg)){
			JSONObject retData = JSONObject.parseObject(obj.getString("retData"));
			int recordCnt = retData.getIntValue("recordCnt");
			if(recordCnt > 0){
				JSONArray data = JSONObject.parseArray(retData.getString("data"));
				for(int i=0;i<recordCnt;i++){
					OpenNo open = new OpenNo();
					JSONObject cObj = JSONObject.parseObject(data.get(i).toString());
					String sNo = cObj.getString("expect");
					open.setsNo(sNo);
					String sTime = cObj.getString("openTime");
					String openCode = cObj.getString("openCode");
					String[] color =  openCode.split("\\+");
					String[] red = color[0].split(",");
					open.setRedColor1(red[0]);
					open.setRedColor2(red[1]);
					open.setRedColor3(red[2]);
					open.setRedColor4(red[3]);
					open.setRedColor5(red[4]);
					open.setRedColor6(red[5]);
					open.setBuleColor1(color[1]);
					lOpen.add(open);
					
					ServiceNo ser = serviceNoDao.getOpenBysNo(sNo);
					if(ser == null){
						ser = new ServiceNo();
						ser.setsNo(sNo);
						ser.setsDate(sTime.split(" ")[0]);
						serviceNoDao.Save(ser);
					}
				}
			}
		}
	 
	 if(lOpen != null && lOpen.size() > 0){
		 return lOpen.get(0);
	 }else{
		 return null;
	 }
	  
   } 
   /**
	 * 自动获取每一期开奖结果
	 * @param httpUrl
	 * @param httpArg
	 * @return
	 */
	public static String request(String httpUrl, String httpArg) {
	    BufferedReader reader = null;
	    String result = null;
	    StringBuffer sbf = new StringBuffer();
	    httpUrl = httpUrl + "?" + httpArg;

	    try {
	        URL url = new URL(httpUrl);
	        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	        connection.setRequestMethod("GET");
	        // 填入apikey到HTTP header
	        connection.setRequestProperty("apikey","c54d451ba7a2861148601f5d6b774cca");
	        connection.connect();
	        InputStream is = connection.getInputStream();
	        reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
	        String strRead = null;
	        while ((strRead = reader.readLine()) != null) {
	            sbf.append(strRead);
	            sbf.append("\r\n");
	        }
	        reader.close();
	        result = sbf.toString();
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    return result;
	}

	/**
	 * 获取最大记录
	 * @return
	 */
	public void getMaxUserNo(ModelMap model) {
		
		String sNo = userNoDao.getMaxUserNo();
		if(sNo != null && !"".equals(sNo)){
			model.addAttribute("sNo", sNo);
		}else{
			model.addAttribute("sNo", "2015068");
		}
	}

}
